<?php
/**
 * Created by PhpStorm.
 * User: xi
 * Date: 16/2/23
 * Time: AM9:43
 */

namespace Api\Controller;


use Admin\Model\UsersModel;
use Admin\Model\WechatBindInfoModel;
use Think\Cache;
use Think\Controller;
use Api\Util;
use Admin\Model\IntegralLogModel;
use Api\Util\Helper;
use Api\Util\Aes;
use Org\Net\Http;
use Api\Util\Wechat;

use Api\Util\OpensslEncryptHelper;

class ApiUserController extends  Controller{

    private $uid_rtn_platforms ;

    public function __construct()
    {
        $this->uid_rtn_platforms = C('uid_rtn_platforms');
    }

    public function login(){
        $uid_rtn_platforms = $this->uid_rtn_platforms;
        $type = $_GET['type'];
        Helper::log($_GET);
        $platform = $_GET['platform']?$_GET['platform']:'茄子商城';//0 代表wenda  1代表 茄子营养师  2 代表app
        $callbackUrl = $_GET['callbackUrl'];

        if($type == 'phone'){
            $this->assign('website',$callbackUrl);
            $this->assign('platform',$platform);
            $this->display('./login');
        }else if($type == 'wechat'){
            $code = $_GET['code'];
            $scope = $_GET['scope'];
            if(!$scope) $scope = 'snsapi_base';
            $wechatModel = new \Api\Util\Wechat();
            $user = $wechatModel->authorize($callbackUrl,$platform,$type,$code,$scope);
            Helper::log($user);
            $redis_info = C('REDIS');
            $cache = Cache::getInstance('Redis', $redis_info);
            $uid = $user['uid'];
            $salt = $user['salt'];
            $expire = time()+C('COOKIE_EXPIRE');

            cookie('login_key',null);
            $auth_key =  Helper::get_auth_cookie($user['openid'], $uid, $salt, $expire);
            Helper::log('auth key ======>'.$auth_key);
            $expire = C('COOKIE_EXPIRE');
            cookie('login_key', $auth_key, $expire, '/', 'qiezilife.com');
            $redis_key = C('REDIS_PREFIX').C('REDIS_USER_PREFIX').$uid;
            if(!$cache->exists($redis_key)){
                $cache->set($redis_key,json_encode($user));
            }
            $callbackUrl = base64_decode($callbackUrl);
            //由于使用laravel框架用户信息无法从cookie中获取
            Helper::log('uid_rtn_platforms ======>');
            Helper::log($uid_rtn_platforms);
            Helper::log('platform ======>');
            Helper::log($platform);
            if(in_array($platform,$uid_rtn_platforms) ){
                $str = $user['openid'].'|'.$uid.'|'.$salt.'|'.$expire;
                $user_auth_key = urlencode(base64_encode($str));
                cookie('cookie_key',null);
                $other_key = 'cookie_key';
                $auth = C('SECRET_KEY');
                $user_auth_key = Aes::encode($auth,$user_auth_key);
                cookie('cookie_key', $user_auth_key, $expire, '/', 'qiezilife.com');
                if(in_array($platform,$uid_rtn_platforms)){
                    $callbackUrl = $callbackUrl.'/'.$uid;
                }
            }
            Helper::log('callbackUrl ======>'.$callbackUrl);
            header('Location: '.$callbackUrl);
            die(0);
        }
    }



    public function wxaLogin()
    {
        if(!$_GET['user']){
            $result = [
                'errcode' => -1,
                'msg' => 'param user is invalid',
            ];
            $this->ajaxReturn($result,'json');
            die(0);
        }
        //解密
        $userDataJson = $_GET['user'];
        if(!$userEncodeData = OpensslEncryptHelper::decryptWithOpenssl($userDataJson)){
            $result = [
                'errcode' => -1,
                'msg' => 'param user is incorrect',
            ];
            $this->ajaxReturn($result,'json');
            die(0);
        }
        if(!$userData = json_decode($userEncodeData,true)){
            $result = [
                'errcode' => -1,
                'msg' => 'json decode error',
            ];
            $this->ajaxReturn($result,'json');
            die(0);
        }
        $where["wx_union_id"] =  $userData['unionId'];

        //圈子小程序的数据迁移部分的公众号appid
        if(isset($userData['circle_gh_appid'])){
            $where["from_appid"] =  $userData['circle_gh_appid'];
        }

        $weiModel = new \Admin\Model\UsersWeixinModel();
        $userModel = new UsersModel();
        if($user = $userModel->getUser($where)){
            $encodeUser = json_encode($user);
        }else{
            //
            $insertUserData = array();
            $username = $userData['nickName'];
            if($userModel->check_username($username)){
                $username .= '_' . rand(1, 999);
            }

            $insertUserData['user_name'] = $username;
            $insertUserData['password'] = md5(rand(111111, 999999999));
            //$data['avatar_file'] = $userObj['headimgurl'];
            $insertUserData['sex'] = $userData['gender'];
            $insertUserData['province'] = $userData['province'];
            $insertUserData['city'] = $userData['city'];
            $insertUserData['country'] = $userData['country'];
            $insertUserData['reg_time'] = time();
            $insertUserData['from_type'] = 'wxminiapp';
            $insertUserData['from_platform'] = 'wxminiapp';
            $appid = $userData['watermark']['appid'];
            $insertUserData['from_appid'] = $appid;
            $insertUserData['wx_union_id'] = $userData['unionId'];
            $uid = $userModel->data($insertUserData)->add();

            $weixinData['openid'] = $userData['openId'];;
            $weixinData['uid'] = $uid;
            $weixinData['wx_appid'] = $appid;
            $weixinData['wx_header'] = isset($userData['avatarUrl'])?$userData['avatarUrl']:"";
            $weiModel->data($weixinData)->add();

            $startTime = time();
            //判断是否要做切换
            $cutAvatar = isset($userData['cut_avatar'])?false:true;
            if($cutAvatar){
                Helper::log('begin to cut avatar==============>');
                $avater_path = C('AVATAR_PATH');

                $rootPath = realpath(__ROOT__).$avater_path;
                $path = $rootPath.$userModel->get_avatar($uid,'real',1);
                Helper::mkDirs($path);
//            $avatar_url = str_replace('wx.qlogo.cn', '180.163.26.115', $userData['avatarUrl']);
//                $avatar_url = str_replace('wx.qlogo.cn', '180.163.26.115', $userData['avatarUrl']);
                $avatar_url = $userData['avatarUrl'];
                Http::curlDownload($avatar_url,$path.$userModel->get_avatar($uid,'real',2).'.jpg');
                $image = new \Think\Image();
                $size = filesize($path.$userModel->get_avatar($uid,'real',2).'.jpg');
                if($size > 0){
                    $image->open($path.$userModel->get_avatar($uid,'real',2).'.jpg');
                    $image->thumb(100, 100,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'max',0).'.jpg');
                    $image->thumb(50, 50,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'mid',0).'.jpg');
                    $image->thumb(32, 32,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'min',0).'.jpg');
                    $updateData = array();
                    $avatar_file = $userModel->get_avatar($uid,'max',0).'.jpg';
                    $updateData['uid'] = $uid;
                    $updateData['avatar_file'] = $avatar_file;
                    $r = $userModel->save($updateData);
                }
            }
            $endTime = time();
            Helper::log('cut avatar spend time ==================>'.($endTime - $startTime));
            $insertUserData['uid'] = $uid;
            $insertUserData['avatar'] = $avatar_file;
            $encodeUser = json_encode($insertUserData);
        }
        $value = OpensslEncryptHelper::encryptWithOpenssl($encodeUser);
        $result = [
            'errcode' => 200,
            'msg' => 'SUCCESS',
            'data' => $value
        ];
        $this->ajaxReturn($result,'json');
    }


    public function batchSynUserInfo(){
        if(!$appid = $_GET['appid']){
            $result =  [
                'errcode' => -1,
                'msg' => 'param appid is invalid',
            ];
            $this->ajaxReturn($result,'json');
            die(0);
        }
        $userModel = new UsersModel();
        $where['from_appid'] = $appid;
        $list = $userModel->getUserList($where);
        if($list){
            $updateData = [];
            $wechat = new Wechat();
            $bindInfoModel = new \Api\Model\WechatBindInfoModel();
            $wxModel = new \Admin\Model\UsersWeixinModel();
            $bindInfo = $bindInfoModel->getByAppid($appid);
            if($bindInfo){
                $data = array_chunk($list,100);
                foreach ($data as $key =>$subList){
                    $uids = array_column($subList,'uid');
                    $uidStr = implode(",",$uids);
                    $whereWx['uid'] = array('in',$uidStr);

                    $userWxList = $wxModel->getUserList($whereWx);
                    $userMapping = [];
                    foreach ($userWxList as $wxu){
                        $userMapping[$wxu['openid']] = $wxu['uid'];
                    }

                    $openids = array_column($userWxList,'openid');
                    if($userInfoList = $wechat->batchGetUserInfo($appid,$bindInfo['appsecret'],$openids)){
                        foreach ($userInfoList as $user){
                            if(isset($user['unionid'])){
                                $obj['uid'] = $userMapping[$user['openid']];
                                $obj['wx_union_id'] = $userMapping[$user['unionid']];
                                array_push($updateData,$obj);
                            }

                        }
                    }
                }

                if($updateData){
                    $chunkData = array_chunk($updateData,1000);
                    foreach ($chunkData as $data){
                        $userModel->saveAll($data,'users');
                    }
                }
            }
        }

        $result =  [
            'errcode' => 200,
            'msg' => 'SUCCESS',
            'data' => $data
        ];
        $this->ajaxReturn($result,'json');
    }

    public function syncWechatUnionId(){
        if(!$uid = $_GET['uid']){
            $result =  [
                'errcode' => -1,
                'msg' => 'param uid is invalid',
            ];
            $this->ajaxReturn($result,'json');
            die(0);
        }
        if(!$appid = $_GET['appid']){
            $result = [
                'errcode' => -1,
                'msg' => 'param appid is invalid',
            ];

            $this->ajaxReturn($result,'json');
            die(0);
        }
        if(!$openid = $_GET['openid']){
            $result =  [
                'errcode' => -1,
                'msg' => 'param appid is invalid',
            ];
            $this->ajaxReturn($result,'json');
            die(0);
        }

        $userModel = new UsersModel();
        $where['uid'] = $uid;
        $unionId = "";
        if($user = $userModel->getUser($where)){
            if(!$unionId = $user['wx_union_id']){
                $bindInfoModel = new \Api\Model\WechatBindInfoModel();
                $bindInfo = $bindInfoModel->getByAppid($appid);
                $wechat = new Wechat();
                if($userInfo = $wechat->getWeixinUserInfo($bindInfo['appid'],$bindInfo['appsecret'],$openid)){
                    if(isset($userInfo['errcode'])){
                        $result =  [
                            'errcode' => -1,
                            'msg' => $userInfo['errcode'].','.$userInfo['errmsg'],
                        ];
                        $this->ajaxReturn($result,'json');
                        die(0);
                    }

                    if(isset($userInfo['unionid'])){
                        $unionId = $userInfo['unionid'];
                        $data['wx_union_id'] = $unionId;
                        $userModel->where($where)->save($data);
                    }

                }
            }
        }
        $rtn['union_id'] = $unionId;
        $result = [
            'errcode' => 200,
            'msg' => 'SUCCESS',
            'data' => $rtn
        ];
        $this->ajaxReturn($result,'json');
    }

    public function syncUserInfo()
    {
        if(!$_GET['user']){
            $result = [
                'errcode' => -1,
                'msg' => 'param user is invalid',
            ];
            $this->ajaxReturn($result,'json');
            die(0);
        }
        //解密
        $userDataJson = $_GET['user'];
        if(!$userEncodeData = OpensslEncryptHelper::decryptWithOpenssl($userDataJson)){
            $result = [
                'errcode' => -1,
                'msg' => 'param user is incorrect',
            ];
            $this->ajaxReturn($result,'json');
            die(0);
        }
        if(!$userData = json_decode($userEncodeData,true)){
            $result = [
                'errcode' => -1,
                'msg' => 'json decode error',
            ];
            $this->ajaxReturn($result,'json');
            die(0);
        }
        $where["uid"] =  $userData['uid'];
        $userModel = new UsersModel();
        //同步用户的手机号码的同时，需要同步同一个unionid所对应的手机号码
        $saveData = array();
        foreach ($userData as $key => $val){
            if($key != 'uid'){
                $saveData[$key] = $val;
            }
        }
        if($user = $userModel->getUser($where)){
            //覆盖保存
            $result1 = $userModel->where($where)->save($saveData);
            if(!empty($user['wx_union_id'])){
                $unionid = $user['wx_union_id'];
                $unionWhere['wx_union_id'] = $unionid;
                $result2 = $userModel->where($unionWhere)->save($saveData);
            }
        }
        $result = [
            'errcode' => 200,
            'msg' => 'SUCCESS',
            'data' => array(
                'result1' => $result1,
                'result2' => $result2,
            )
        ];
        $this->ajaxReturn($result,'json');
    }

    public function getUserInfoByPhone()
    {
        if(!$_GET['param']
            || !$encodeData = OpensslEncryptHelper::decryptWithOpenssl($_GET['param'])){
            $result = [
                'errcode' => -1,
                'msg' => '参数异常',
            ];
            $this->ajaxReturn($result,'json');
            die(0);
        }
        if(!$data = json_decode($encodeData,true)){
            $result = [
                'errcode' => -1,
                'msg' => 'json decode error',
            ];
            $this->ajaxReturn($result,'json');
            die(0);
        }
        if (!$data['phone']) {
            $result = [
                'errcode' => -1,
                'msg' => '参数异常',
            ];
            $this->ajaxReturn($result,'json');
            die(0);
        }
        $where["mobile"] =  $data['phone'];
        $userModel = new UsersModel();

        $result = [
            'errcode' => 200,
            'msg' => 'SUCCESS',
            'data' => [
                'user' => $userModel->getUser($where)
            ],
        ];
        $this->ajaxReturn($result,'json');
    }

    public  function doPhoneLogin(){
        $uid_rtn_platforms = $this->uid_rtn_platforms;;
        $session_code = session('code');
        $mobile = I("post.mobile");
        $code = I("post.code");
        $website = base64_decode(I("post.url"));
        $from_platform = I("post.platform");
        $data = array();
        Helper::log('from_platform ======>'.$from_platform);
        Helper::log('website ======>'.$website);
        if(!$code){
            $data['state'] = -1;
            $data['msg'] = '请输入验证码';
        }else{

            $cache_mobile =  explode(',',$session_code)[0];
            $cache_code =  explode(',',$session_code)[1];

            if($cache_mobile == $mobile && $cache_code==$code){
                $where = array();
                $where["mobile"] =  $mobile;
                $userModel = new UsersModel();
                $user = $userModel->getUser($where);
                if(!$user){
                    $cn_operators = array('130'=>'41', '131'=>'42', '132'=>'43', '133'=>'44', '134'=>'45', '135'=>'46', '136'=>'47', '137'=>'48', '138'=>'49', '139'=>'33', '150'=>'11', '151'=>'12', '152'=>'13', '153'=>'14', '155'=>'15', '156'=>'16', '157'=>'17', '158'=>'18', '159'=>'19', '180'=>'34', '181'=>'21', '182'=>'22', '183'=>'23', '184'=>'24', '185'=>'25', '186'=>'26', '187'=>'27', '188'=>'28', '189'=>'29', '176'=>'35', '177'=>'31', '178'=>'32');
                    // create new account with this mobile
                    $operator = substr($mobile, 0, 3);
                    $num = substr($mobile, 3, 4);
                    $sufix = substr($mobile, 7, 4);
                    $prefix = intval($cn_operators[$operator])*intval($num);
                    $prefix = sprintf('%06d', $prefix);
                    $name = 'm'.$prefix.$sufix;
                    $db_user = array();
                    $db_user['mobile'] =  $mobile;
                    $db_user['user_name'] = $name;
                    $db_user['from_platform']= $from_platform;
                    $db_user['reg_time'] = time();
                    $db_user['sex'] = 2;
                    $db_user['from_type'] = 'mobile';
                    $db_user['password'] = md5(rand(111111, 999999999));
                    $uid = $userModel->data($db_user)->add();
                    $user = $userModel->getUser($where);
                }
                $redis_info = C('REDIS');
                $cache = Cache::getInstance('Redis', $redis_info);
                $hash_key =  md5($mobile);
                $cache->rm($hash_key);
                cookie('login_key',null);
                $expire = 2 * 24 * 60 * 60;
                cookie('login_key',$hash_key,$expire,'/','qiezilife.com');
                $cache->set($hash_key,json_encode($user));
                $data['state'] = 1;
                Helper::log('before website===>'.$website);
                if(in_array($from_platform,$uid_rtn_platforms) ){
                    $website = $website.'/'.$user['uid'];
                }
                Helper::log('after website===>'.$website);
                $data['msg'] = $website;

            }else{
                $data['state'] = -1;
                $data['msg'] = '验证码错误';
            }
        }
        
        $this->ajaxReturn($data,'json');
    }
    
    /**
     * 登出选项
     */
    public function logout(){
        // 清除
        session_unset(); 
        session_destroy();
        $callbackUrl = base64_decode(I("get.callbackUrl"));
        cookie('login_key',null);
        header('Location: '.$callbackUrl);
    }

    public  function  updateUserIntegral(){

        $data= array();
        $result = array();
        $integralLogModel = new IntegralLogModel();//M('IntegralLog');
        $userModel = new UsersModel();
        $secret = C('SECRET_KEY');

        $api_key = $_POST['api_key'];
        $integral = $_POST['integral'];
        $opt = $_POST['opt'];//-1 代表 1代表+
        $uid = $_POST['uid'];
        $platform = $_POST['platform'];//0 代表wenda  1代表 茄子营养师  2 代表app
        $action = $_POST['action'];//具体操作积分的动作
        $result['state'] = -1;
        $result['msg'] = '';
        $where = "uid=".$uid;
	error_log('posted data:'.json_encode($_POST));

        if($api_key == ''){
            $result['state'] = -1;
            $result['msg'] = "api_key 不能为空";
            $this->ajaxReturn($result,'json');
            die(0);
        }
        if(!$integral || !$uid ){
            $result['state'] = -1;
            $result['msg'] = "用户 id，或者 积分不能为空";
            $this->ajaxReturn($result,'json');
            die(0);

        }
	error_log('opt:'.$opt);
        if(!$opt){
            $opt = 1;
        }
        $user = $userModel->where($where)->find();
        if(!$user){
            $result['state'] = -1;
            $result['msg'] = "用户不存在";
            $this->ajaxReturn($result,'json');
            die(0);
        }
        $currentIntegral = $user['integral'];
        $key = md5($uid.$user['password'].$secret);
        if($key != $api_key){

            $result['state'] = -1;
            $result['msg'] = "api_key 不对";
            $this->ajaxReturn($result,'json');
            die(0);
        }

        if($opt > 0){
            $id = $userModel->where($where)->setInc('integral',$integral);
        }else{

            if($currentIntegral >= $integral){
                $id = $userModel->where($where)->setDec('integral',$integral);
            }else{
                $result['state'] = -1;
                $result['msg'] = "积分不够";
                $this->ajaxReturn($result,'json');
                die(0);
            }
        }

        if($id > 0){error_log('change points:'.$currentIntegral.' by '.$opt);
            $data['uid'] = $uid;
            $data['action'] = $action;
            $data['time'] = time();
            $data['platform'] = $platform;
            $data['integral'] = $integral;
            $integralLogModel->data($data)->add();
            if($opt>0){
                $currentIntegral = $currentIntegral+$integral;
            }else{
                $currentIntegral = $currentIntegral-$integral;

            }
        }
        $result['state'] = 1;
        $result['msg'] = $currentIntegral;
        $this->ajaxReturn($result,'json');
        die(0);
    }


    public function getUserIntegral(){

        $uid = $_POST['uid'];
        $userModel = new UsersModel();
        $where = "uid=".$uid;
        $user = $userModel->where($where)->find();
        $result = array();

        if(!$user){
            $result['state'] = -1;
            $result['msg'] = "用户不存在";
            $this->ajaxReturn($result,'json');
            die(0);
        }

        $result['state'] = 1;
        $result['msg'] = $user['integral'];
        $this->ajaxReturn($result,'json');
    }

    /**
     * 更改用户信息 (不包括积分)
     */
    public  function  updateUserInfo(){

        $userModel =  new UsersModel();
        //茄子商场，商城,问答
        //integral,user_name,sex，province,city,country,real_name
        $result = array();
        $data = array();
        $uid = $_POST['uid'];
        if(!$uid) $result['state'] = -1;
        $where = "uid = ".$uid;
        $integral = $_POST['integral'];
        $user_name = $_POST['user_name'];
        $sex = $_POST['sex'];
        $province = $_POST['province'];
        $city = $_POST['city'];
        $country =  $_POST['country'];
        $real_name = $_POST['real_name'];
        $api_key = $_POST['api_key'];

        if($api_key == ''){
            $result['state'] = -1;
            $result['msg'] = "api_key 不能为空";
            $this->ajaxReturn($result,'json');
            die(0);
        }

        $secret = C('SECRET_KEY');
        $selectWhere = array();
        $selectWhere['uid'] = $uid;
        $user = $userModel->getUser($selectWhere);
        if(!$user){
            $result['state'] = -1;
            $result['msg'] = "api_key 用户不存在";
            $this->ajaxReturn($result,'json');
            die(0);
        }

        $key = md5($uid.$user['password'].$secret);
        if($key != $api_key){

            $result['state'] = -1;
            $result['msg'] = "api_key 不对";
            $this->ajaxReturn($result,'json');
            die(0);
        }

        if($user_name){
            $data['user_name'] = $user_name;
        }
        if($sex){
            $data['sex'] = $sex;
        }
        if($province){
            $data['province'] = $province;
        }if($city){
            $data['city'] = $city;
        }
        if($country){
            $data['country'] = $country;
        }
        if($real_name){
            $data['real_name'] = $real_name;
        }

        $id = $userModel->where($where)->save($data);
        $result['msg'] = "更新失败";
        if($id > 0){
            $result['state'] = 1;
            $result['msg'] = "更新成功";
        }
        $this->ajaxReturn($result,'json');
    }

    //修改头像 上传文件
    public function uploadFile(){
        $userModel =  new UsersModel();
        $uid = $_POST['uid'];
        $path = $userModel->get_avatar($uid,'min',1);
        $fileName = $userModel->get_avatar($uid,'real',2);
        $config = array(
            'maxSize'    =>    3145728,
            'rootPath'   =>    './uploads/avatar/',
            'savePath'   =>    $path,
            'saveName'   =>    $fileName,
            'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
            'autoSub'    =>    true,
            'subName'    =>    '',

        );
        $file = realpath(__ROOT__).'/uploads/avatar/'.$path.$fileName.'.jpg';

        if (file_exists($file)) {

            $result = @unlink ($file);
            $max =  realpath(__ROOT__).'/uploads/avatar/'.$path.$userModel->get_avatar($uid,'max',2).'.jpg';
            $mid =  realpath(__ROOT__).'/uploads/avatar/'.$path.$userModel->get_avatar($uid,'mid',2).'.jpg';
            $min =  realpath(__ROOT__).'/uploads/avatar/'.$path.$userModel->get_avatar($uid,'min',2).'.jpg';
            @unlink ($file);
            @unlink ($max);
            @unlink ($mid);
            @unlink ($min);

        }
        $upload = new \Think\Upload($config);
        $info = $upload->uploadOne($_FILES['file']);

        \Think\Log::record('===上传文件==='.$upload->getError());

        //echo "uid======".$uid."info=".json_encode($info);
        $result = array();
        $result['state'] = -1;
        $result['msg'] = "上传失败";
        if($info){


            $result['state'] = 1;
            $result['msg'] = "上传成功";
            $path = $info['savepath'].$info['savename'];
            $where = "uid = ".$uid;
            $data = array();
            $data['avatar_file'] = $userModel->get_avatar($uid,min,0);
            $image = new \Think\Image();

            $imgRootPath = realpath(__ROOT__).'/uploads/avatar/';
            $image->open($imgRootPath.$path);

            $image->thumb(100, 100,\Think\Image::IMAGE_THUMB_CENTER)->save($imgRootPath.$userModel->get_avatar($uid,'max',0).'.jpg');
            $image->thumb(50, 50,\Think\Image::IMAGE_THUMB_CENTER)->save($imgRootPath.$userModel->get_avatar($uid,'mid',0).'.jpg');
            $image->thumb(32, 32,\Think\Image::IMAGE_THUMB_CENTER)->save($imgRootPath.$userModel->get_avatar($uid,'min',0).'.jpg');

            $id = $userModel->where($where)->save($data);
        }

        $this->ajaxReturn($result,'json');
    }


    public function  ajaxGetCode(){

        $mobile = $_POST['mobile'];
        $url = "http://account.qiezilife.com/Api/Sms/sendSms?mobile=".$mobile;
        $data = Util\Helper::curl_request($url);
        $result = array();
        if($data){
            //
            $data = json_decode($data);
            $state = $data->state;
            $code = $data->code;
            if($state == 0){
                session('code',$mobile.",".$code);  //设置session
                $result['code'] = 1;
                $result['msg'] = '发送成功';
            }else{
                $result['code'] = -1;
                $result['msg'] = '发送失败';
            }
        }else{
            $result['code'] = -1;
            $result['msg'] = '发送失败';
        }

        $this->ajaxReturn($data,'json');
    }




    //判断是否是新用户
    public function isNewUser(){

        $openid = $_POST['openid'];
        $where_w = array();
        $where_w["openid"] =  $openid;
        $weiModel = new \Admin\Model\UsersWeixinModel();
        $user_w = $weiModel->getUser($where_w);error_log('check user ret:'.json_encode($user_w));
        $state = -1;

        if($user_w){
            $state = 1;
        }

        $data = array(
            'state' => $state
        );
        $this->ajaxReturn($data,'json');

    }

    //注册新用户
    public function createUser(){

        $userModel = new \Admin\Model\UsersModel();
        $weiModel = new \Admin\Model\UsersWeixinModel();
        $avater_path = C('AVATAR_PATH');
        $userJson = $_POST['user'];
        $userObj = json_decode($userJson, true);
        $data = array();

        if (strlen(trim($userObj['nickname'])) == 0) {
            // no nickname? using default one
            $userObj['nickname'] = '茄子粉';
        }


        $username = $userObj['nickname'];
        if($userModel->check_username($username)){
            $username .= '_' . rand(1, 999);
        }
        $data['user_name'] = $username;

        $data['password'] = md5(rand(111111, 999999999));

        $data['sex'] = $userObj['sex'];
        $data['province'] = $userObj['province'];
        $data['city'] = $userObj['city'];
        $data['country'] = $userObj['country'];
        $data['reg_time'] = time();
        $data['referer_uid'] = $_POST['from_uid'];
        $data['from_type'] = 'weixin';
        $data['from_platform'] = $_POST['from_platform'];
        $uid = $userModel->data($data)->add();
        $data_w['openid'] = $userObj['openid'];
        $data_w['uid'] = $uid;
        $weiModel->data($data_w)->add();

        $where_u = array();
        $where_u['uid'] = $uid;
        $user = $userModel->getUser($where_u);
        $user['openid'] = $userObj['openid'];

        $state = -1;
        $hash_key = '0';
        if($uid > 0){
            $state = 1;
            // set user login
	    $redis_info = C('REDIS');
            $cache = Cache::getInstance('Redis', $redis_info);
            $hash_key =  md5($user['openid']);
            $cache->rm($hash_key);
            $expire = 2 * 24 * 60 * 60;
            $cache->set($hash_key,json_encode($user));
        }
        $data = array(
            'state' => $state,
            'key' => $hash_key,
        );
        //$this->ajaxReturn($data,'json');
        echo json_encode($data);
        
        // now get user avatar
        $rootPath = realpath(__ROOT__).$avater_path;
        $path = $rootPath.$userModel->get_avatar($uid,'real',1);
        Helper::mkDirs($path);
        
        $avatar_url = str_replace('wx.qlogo.cn', '180.163.26.115', $userObj['headimgurl']);
        Http::curlDownload($avatar_url, $path.$userModel->get_avatar($uid,'real',2).'.jpg');
        $image = new \Think\Image();
        $size = filesize($path.$userModel->get_avatar($uid,'real',2).'.jpg');
        if($size > 0){
            $image->open($path.$userModel->get_avatar($uid,'real',2).'.jpg');
            $image->thumb(100, 100,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'max',0).'.jpg');
            $image->thumb(50, 50,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'mid',0).'.jpg');
            $image->thumb(32, 32,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'min',0).'.jpg');
            $updateData = array();
            $avatar_file = $userModel->get_avatar($uid,'min',0).'.jpg';
            $updateData['uid'] = $uid;
            $updateData['avatar_file'] = $avatar_file;
            $r = $userModel->save($updateData);
        }
    }


    public function test_clear(){

        $value = $_COOKIE['login_key'];
	$redis_info = C('REDIS');
	$cache = Cache::getInstance('Redis', $redis_info);
        $cache->rm($value);
        cookie('login_key',null);

        echo 'sucess==';
    }
    public function test_check(){

        $key = $_COOKIE['login_key'];
	$redis_info = C('REDIS');
	$cache = Cache::getInstance('Redis', $redis_info);
        $value = $cache->$key;
        cookie('login_key',null);
        echo 'key==='.$key.'====value='.$value;

    }
    
    /**
     * 这个仅用于测试？
     */
    public function update_null(){

        $userModel = new \Admin\Model\UsersModel();
        $list = $userModel->query("select * from users where user_name is null");
        $token = '246Sg50ksATH6ieZaayazB0_EKdj8FKcBkFCdLggD0xnsaTzun5ko9M4yb-nyKjpu7T1yxS51J1-S0w2QqkA_df1aCG5WKIZ8KiHAHLVJeYgFb1v7QI7Iswn1vsoHZHyIGJcACAOMP';
   
        foreach($list as $key=>$val){
          $data = array();
          $wx =   $userModel->query("select * from users_weixin where uid = ".$val['uid']);
          $openid  = $wx[0]['openid'];
          $userInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" . $openid . "&lang=zh_CN";
          $user_result =  Helper::curl_request($userInfoUrl);
          $list[$key]['user'] = $user_result; 
          $list[$key]['openid'] = $openid;           
          $userObj = json_decode($user_result, true);

          $data['uid'] = $val['uid'];
          $username = $userObj['nickname'];
          if($userModel->check_username($username)){
               $username .= '_' . rand(1, 999);
           }
           $data['user_name'] = $username;
           $data['sex'] = $userObj['sex'];
           $data['province'] = $userObj['province'];
           $data['city'] = $userObj['city'];
           $data['country'] = $userObj['country'];
           $r = $userModel->save($data);

           $wenda = "http://wenda.qiezilife.com/account/ajax/sync_user/?user=".json_encode($data);
           $user_result =  Helper::curl_request($wenda);

        }

        echo json_encode($list);

    }


    public function fetch_wx_info(){
        $uid = I('get.uid');
        if(!$uid){
            $result['state'] = -1;
            $result['msg'] = 'uid invailid';
            $result['data'] = null;
            $this->ajaxReturn($result,'json');
            die(0);
        }

        $wechatModel = new \Api\Util\Wechat();
        $wx_user_info = $wechatModel->reset_user_info($uid);
        error_log('wx_user_info========>'.json_encode($wx_user_info));
        $state = $wx_user_info ? 1 : -1;
        $data = array(
            'state' => $state,
            'msg' => 'SUCCESS',
            'data' => $wx_user_info
        );
        $this->ajaxReturn($data,'json');
    }


    public function clear_access_token(){
        $uid = I('get.uid');
        S('ACCESS_TOKEN',null);
        S('ACCESS_TOKEN_TIME',null);
        S('user_info_'.$uid,null);
    }
}
